package com.mjk.common.util;

import com.mjk.common.tools.logger.BizLogger;
import lombok.Data;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;

public class ComputerUtils {
    private ComputerUtils(){}

    public static String getHostName(){
		try{
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostName();
		}catch(Exception e){
			BizLogger.error(e);
		}
		return "";
	}
	
	// 获取mac地址
    public static String getMacAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            byte[] mac;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !netInterface.isUp()
                		||netInterface.getDisplayName().contains("VMware Virtual")
                		||netInterface.getDisplayName().contains("Wireless")) {
                    //do noting
                } else {
                    mac = netInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                        if (!sb.isEmpty()) {
                            return sb.toString();
                        }
                    }
                }
            }
        } catch (Exception e) {
        	BizLogger.error("MAC地址获取失败", e);
        }
        return "";
    }

    // 获取ip地址
    public static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface =  allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !netInterface.isUp()
                		||netInterface.getDisplayName().contains("VMware Virtual")//排除虚拟机
                		//||netInterface.getDisplayName().contains("Wireless")
                		){ //排除无线
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            BizLogger.error("IP地址获取失败", e);
        }
        return "";
    }
    
    /**
     */
    public static ComputerInfo getComputerInfo() {
    	ComputerInfo info = new ComputerInfo();
    	info.setIp(getIpAddress());
    	OperatingSystemMXBean osBean =  ManagementFactory.getOperatingSystemMXBean();
    	com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean;

    	info.setAvailableProcessors(osBean.getAvailableProcessors());
    	info.setSystemLoadAverage(sunOsBean.getProcessCpuLoad());
    	MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        //总共的物理内存
        info.setTotalPhysicalMemory((sunOsBean.getTotalMemorySize()));
        //使用的物理内存
        info.setUsedPhysicalMemory((sunOsBean.getTotalMemorySize() - sunOsBean.getFreeMemorySize() ));
        //空闲的物理内存
        info.setFreePhysicalMemory((sunOsBean.getFreeMemorySize()));
        //堆总内存
        info.setTotalHeadMemory((heapMemoryUsage.getMax()));
        //堆空闲内存
        info.setFreeHeadMemory((heapMemoryUsage.getMax() - heapMemoryUsage.getUsed()));
        String currentDrive = System.getProperty("user.dir");
        File file = new File(currentDrive);
        info.setDiskSpace((file.getFreeSpace()));
        return info;
    }
    public static String formatSize(float size){
        String[] units = {"B","KB","MB","GB","TB"};
        int index =0;
        double formateSize = size;
        while(formateSize>=1024 && index<units.length-1){
            formateSize/=1024;
            index++;
        }
        return String.format("%.2f %s",formateSize,units[index]);
    }
   @Data
   public static class ComputerInfo{
	   /**
	    * 服务名称
	    */
	   private String serviceName;

       private String showName;
	   /**
	    * ip地址
	    */
	   private String ip;
	   /**
	    * 端口信息
	    */
	   private String port;
	   /**
	    * cpu核心线程数
	    */
	   private int availableProcessors ;
	   /**
	    * 获取CPU负载信息
	    */
	   private double systemLoadAverage ;
	   /**
	    * 总物理内存大小
	    */
	   private long totalPhysicalMemory ;
	   /**
	    * 可用物理内存大小
	    */
	   private long freePhysicalMemory ;
       /**
        * 堆内存大小
        */
       private long totalHeadMemory ;
       /**
        * 空闲堆内存大小
        */
       private long freeHeadMemory ;
	   /**
	    * 已使用物理内存大小
	    */
	   private long usedPhysicalMemory ;
       /**
        * 磁盘剩余空间
        */
       private long diskSpace;
       /**
        * 是否可用
        */
       private String enable;
       /**
        * 元信息
        */
       private Map<String, String> mateInfo;
   }
}
